﻿using System;

//
// Created by Arosy on 2021/12/11.
//

//
// Created by Arosy on 2021/12/11.
//




public class JavaNativeInterface
{
	/**
	 * 找到某个Java类中的某个方法
	 * @param klass
	 * @param name
	 * @param descriptor
	 * @return
	 */
	public static MethodInfo getMethod(InstanceKlass klass, string name, string descriptor)
	{
		for (int i = 0; i < klass.getMethodCount(); i++)
		{ //遍历这个klass的所有方法
			MethodInfo m = klass.getMethodInfo() [ i];
			string nameMethod = ((char)klass.getConstantPool().data[m.getNameIndex()]).ToString();
			string descMethod = ((char)klass.getConstantPool().data[m.getDescriptorIndex()]).ToString();
			if (name == nameMethod && descriptor == descriptor)
			{ // 如果这个方法是要找的就return
				return m;
			}
		}
		return null;
	}
	/**
	 * 调用static类型的Java方法
	 * @param javaThread
	 * @param method
	 */
	public static void callStaticMethod(JavaThread javaThread, MethodInfo method)
	{
		Console.Write("===============执行方法开始 :{0} =================\n", method.getMethodName());
		JavaVFrame javaVFrame = new JavaVFrame(); //马上要执行方法了，先创建栈帧
		javaThread.stack.Push(javaVFrame); //栈帧push进线程的栈空间
		BytecodeInterpreter.run(javaThread, method); // 执行方法
		javaThread.stack.Pop(); //将执行完成的栈桢弹出栈空间
		javaVFrame = null; //释放栈桢内存空间
	}
	 /**
	 * invokevirtual 用来调用Java方法
	 * @param javaThread
	 * @param method
	 */
	public static void callVirtual(JavaThread javaThread, MethodInfo method, int paramCount, string[] @params)
	{
		Console.Write("===============执行方法开始 :{0} =================\n", method.getMethodName());
		JavaVFrame javaVFrame = new JavaVFrame(); //马上要执行方法了，先创建栈帧
		for (int i = 1; i <= paramCount; ++i)
		{ //将参数写入局部变量表
			javaVFrame.locals[i] = (CommonValue)(@params[i - 1]);
		}
		javaVFrame.locals[0] = (CommonValue)@params[paramCount]; //非静态方法第一个参数为this指针
		javaThread.stack.Push(javaVFrame); //栈帧push进线程的栈空间
		BytecodeInterpreter.run(javaThread, method); // 执行方法
		javaThread.stack.Pop(); //将执行完成的栈桢弹出栈空间
		javaVFrame = null; //释放栈桢内存空间
	}

	/**
	 * invokevirtual 用来调用Java方法
	 * @param javaThread
	 * @param method
	 */
	public static void callSpecial(JavaThread javaThread, MethodInfo method, int paramCount, string[] @params)
	{
		Console.Write("===============执行方法开始 :{0} =================\n", method.getMethodName());
		JavaVFrame javaVFrame = new JavaVFrame(); //马上要执行方法了，先创建栈帧
		for (int i = 1; i <= paramCount; ++i)
		{ //将参数写入局部变量表
			javaVFrame.locals[i] = (CommonValue)(@params[i - 1]);
		}
		javaVFrame.locals[0] = (CommonValue)@params[paramCount]; //非静态方法第一个参数为this指针
		javaThread.stack.Push(javaVFrame); //栈帧push进线程的栈空间
		BytecodeInterpreter.run(javaThread, method); // 执行方法
		javaThread.stack.Pop(); //将执行完成的栈桢弹出栈空间
		javaVFrame = null; //释放栈桢内存空间
	}
}